import EventManager from "../core/EventManager";
import PopupManager from "../core/PopupManager";
import LogUtil from "../utils/LogUtil";
import { CommonEvents } from "./CommonEvents";
import { ISocket, NetData, ISocketOptions } from "./NetInterface";
import Singleton from "./Singleton";

/*
*   WebSocket封装
*   1. 连接/断开相关接口
*   2. 网络异常回调
*   3. 数据发送与接收
*  
*/
export class WebSock extends Singleton implements ISocket {
    private _ws: WebSocket = null;              // websocket对象

    connect(options: ISocketOptions) {
        if (this._ws) {
            if (this._ws.readyState === WebSocket.CONNECTING) {
                LogUtil.log("websocket connecting, wait for a moment...")
                return false;
            }
        }

        let url = null;
        if (options.url) {
            url = options.url;
        } else {
            let ip = options.ip;
            let port = options.port;
            let protocol = options.protocol;
            url = `${protocol}://${ip}:${port}`;
        }

        this._ws = new WebSocket(url);
        this._ws.binaryType = options.binaryType ? options.binaryType : "arraybuffer";
        this._ws.onmessage = (event: MessageEvent) => {
            this.onMessage(event.data);
        };
        this._ws.onopen = this.onConnected;
        this._ws.onerror = this.onError;
        this._ws.onclose = this.onClosed;
        return true;
    }

    send(buffer: NetData) {
        if (this._ws.readyState == WebSocket.OPEN) {
            this._ws.send(buffer);
            return true;
        }
        return false;
    }

    close(code?: number, reason?: string) {
        this._ws.close(code, reason);
    }

    onConnected(event: Event) {
        LogUtil.log("Connection open ");
        EventManager.emit(CommonEvents.SERVICE_CONNECTED);
    }
    onMessage(msg:any) {
        // LogUtil.log(typeof msg);
        // try {
        //     var data = JSON.parse(msg)
        // } catch (error) {
        //     LogUtil.log(error,msg)
        // }
        EventManager.emit(CommonEvents.SERVICE_MSG, msg);
    }
    onError(event: Event) {
        LogUtil.warn("Connection onerror ");
    }
    onClosed(event: CloseEvent) {
        LogUtil.warn("Connection onclose ");
    }

    private _showToast(msg: string, cb: Function) {
        PopupManager.show('prefabs/PopBox', {
            title: '提示',
            content: msg,
            confirmCallback: () => {
                cb && cb()
            }
        })
    }
}